﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Pixysoft.Framework.Sockets;

namespace Pixysoft.WinForms.TestDriven
{
    public partial class Form_server : Form
    {
        SocketManager manager = null;

        public Form_server()
        {
            InitializeComponent();

            SocketServer.SetCodecFactory(new Pixysoft.Framework.Sockets.Codec.SocketSessionCodecFactory());

            SocketServer.RegisterHandler(new PingHandler());
        }

        private void button1_Click(object sender, EventArgs e)
        {
            SocketServer.Start(int.Parse(textBox_port.Text));
        }

        private void button2_Click(object sender, EventArgs e)
        {
            manager = new SocketManager(textBox_ip.Text, int.Parse(textBox_port.Text), new CallbackMe(this));
            manager.Connect();
        }

        public void AppendReceive(string text)
        {
            textBox_receive.Text += text + "\r\n";
        }

        private void button_sendmessage_Click(object sender, EventArgs e)
        {
            IProtocolMessage message = manager.CreateRequest(1, 1);
            message.ByteBody = Pixysoft.StringCoder.StringToByte(textBox_sent.Text);
            manager.Send(message);
        }

        private void button_stopclient_Click(object sender, EventArgs e)
        {
            manager.Disconnect();
        }
    }

    [ProtocolDeclaration(1, 1)]
    class CallbackMe : IActionHandlerCallback
    {
        Form_server form = null;

        public CallbackMe(Form_server form)
        {
            this.form = form;
        }

        public void Callback(ISocketIoSession session, IProtocolHeader header, byte[] body)
        {
            Pixysoft.MultiThread.WinformInvoker<string>.Invoke(form, form.AppendReceive, StringCoder.ByteToString(body));
        }
    }

    [ProtocolDeclaration(1, 1)]
    class PingHandler : IActionHandler
    {
        public bool Handle(ISocketIoSession session, IProtocolHeader header, byte[] body)
        {
            IProtocolMessage response = session.CreateResponse(header);
            response.ByteBody = body;
            session.Send(response);
            return true;
        }
    }
}